package top.zerozoo.learn.grade.dao.impl;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import top.zerozoo.learn.grade.dao.CourseScoreDao;
import top.zerozoo.learn.grade.entity.CourseScore;
import top.zerozoo.learn.grade.entity.StudentBaseInfo;
import top.zerozoo.learn.grade.util.JdbcUtils;
import top.zerozoo.learn.grade.vo.QueryScoreCondition;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CourseScoreDaoImpl implements CourseScoreDao {

    private JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());

    @Override
    public CourseScore findById(int id) {
        final String sql = "select * from courseScore where id = ?";
        CourseScore result;
        try {
            result = template.queryForObject(sql, new BeanPropertyRowMapper<>(CourseScore.class), id);
        } catch (IncorrectResultSizeDataAccessException ex) {
            return null;
        }
        return result;
    }

    @Override
    public List<CourseScore> findByStudentID(int studentID) {
        final String sql = "select * from courseScore where studentID = ?";
        List<CourseScore> result = template.query(sql, new BeanPropertyRowMapper<>(CourseScore.class), studentID);
        return result;
    }

    @Override
    public int insert(CourseScore courseScore) {
        final String sql = "insert into courseScore(studentID,name,score) value(?,?,?)";
        return template.update(sql,
                courseScore.getStudentID(),
                courseScore.getName(),
                courseScore.getScore());
    }

    @Override
    public int update(CourseScore courseScore) {
        final String sql = "update courseScore set studentID = ?,name = ?,score = ? where id = ?";
        return template.update(sql,
                courseScore.getStudentID(),
                courseScore.getName(),
                courseScore.getScore(),
                courseScore.getId());
    }

    @Override
    public int deleteById(int id) {
        final String sql = "delete from courseScore where id = ?";
        return template.update(sql, id);
    }

    @Override
    public int count(QueryScoreCondition condition) {
        final String sql = "select count(*) from courseScore where studentID = ?";
        return template.queryForObject(sql, Integer.class, condition.getStudentID());
    }

    @Override
    public List<CourseScore> find(int start, int rows, QueryScoreCondition condition) {
        final String sql = "select * from courseScore where studentID = ? limit " + start + "," + rows;

        return template.query(sql, new BeanPropertyRowMapper<>(CourseScore.class),  condition.getStudentID());
    }
}
